package com.gis.controller;

import com.gis.entity.LayerData;
import com.gis.result.ResponseResult;
import com.gis.service.LayerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/task")
@Tag(name = "任务流程")
public class TaskController {
    @Value("${files.dir}/${files.relative-save-dir}/${files.task}")
    private String taskDir;
    private final LayerService layerService;

    /**
     * 获取任务结果 逻辑都写Controller里了 省事
     * @param taskId 任务id
     * @param response
     */
    @Operation(summary = "下载任务结果")
    @GetMapping("/getTaskResult")
    public void getTaskResult(@RequestParam String taskId, HttpServletResponse response) {
        List<File> files = getFiles(taskId);
        if (files.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // 设置 ZIP 文件名
        String zipFileName = taskId + "_results.zip";
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + "\"");
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            byte[] buffer = new byte[1024];
            for (File file : files) {
                try (FileInputStream fis = new FileInputStream(file)) {
                    ZipEntry zipEntry = new ZipEntry(file.getName());
                    zipOut.putNextEntry(zipEntry);
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        zipOut.write(buffer, 0, bytesRead);
                    }
                    zipOut.closeEntry();
                }
            }
            zipOut.finish();
        } catch (IOException e) {
            log.error("文件压缩或发送失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 上传任务结果
     * @param taskId
     * @return
     */
    @Operation(summary = "上传任务结果")
    @GetMapping("/uploadTaskResult")
    public ResponseResult<?> uploadTaskResult(@RequestParam String taskId) {
        List<File> files = getFiles(taskId);
        List<LayerData> result = new ArrayList<>();
        if (files.isEmpty()) {
            return ResponseResult.fail("无输出文件或任务输出超时失效");
        }
        for (File file : files) {
            String fileName = file.getName();
            int dotIndex = fileName.lastIndexOf('.');
            String fileExtension = dotIndex > 0 ? fileName.substring(dotIndex + 1) : "";
            MultipartFile multipartFile = null;
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                if (fileExtension.equals("nc")) {
                    result.add(layerService.publishLayer(multipartFile, "NetCDF", "Normalize-0-1-Style"));
                }else if(fileExtension.equals("png")){
                    result.add(layerService.uploadFile(null, multipartFile));
                }else{
                    Map<String, Object> map = Map.of(
                            "msg", "发布图层失败",
                            "code", 500,
                            "data", "输出文件类型错误"
                    );
                    return ResponseResult.fail(map);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                Map<String, Object> map = Map.of(
                        "msg", "上传文件失败",
                        "code", 500,
                        "data", e.getMessage()
                );
                return ResponseResult.fail(map);
            }
        }
        return ResponseResult.success(result);
    }


    private List<File> getFiles(String taskId){
        // 读取任务文件夹
        String taskResultPath = taskDir + "/" + taskId + "/result";
        List<File> files;
        try (Stream<Path> paths = Files.walk(Paths.get(taskResultPath))) {
            files = paths
                    .filter(Files::isRegularFile) // 只保留文件（不包括目录）
                    .map(Path::toFile)
                    .collect(Collectors.toList());
        } catch (IOException e) {
            log.error("读取目录失败: " + taskResultPath, e);
            files = Collections.emptyList(); // 失败时返回空列表
        }
        return files;
    }

}
